package br.com.informatos.httpandjason;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		TextView txtName = (TextView) findViewById(R.id.txt_name);
		TextView txtFone = (TextView) findViewById(R.id.txt_fone);
		TextView txtAdress = (TextView) findViewById(R.id.txt_adress);
		TextView txtCity = (TextView) findViewById(R.id.txt_city);
		TextView txtLikes = (TextView) findViewById(R.id.txt_likes);

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		String response = makeRequest("http://graph.facebook.com/k19treinamentos");

		try{
			JSONObject json = new JSONObject(response);
			String name = json.getString("name");
			String fone = json.getString("phone");
			int likes = json.getInt("likes");
			String adress = json.getJSONObject("location").getString("street");
			String city = json.getJSONObject("location").getString("city");

			txtName.setText(name);
			txtFone.setText(getString(R.string.lb_fone, fone));
			txtAdress.setText(getString(R.string.lb_adress, adress));
			txtCity.setText(getString(R.string.lb_city, city));
			txtLikes.setText(getString(R.string.lb_Likes, likes));

		}catch(JSONException e){
			e.printStackTrace();
		}

	}

	private String makeRequest(String urlAdress){
		HttpURLConnection con = null;
		URL url = null;
		String response = null;
		try{
			url = new URL(urlAdress);
			con = (HttpURLConnection) url.openConnection();
			response = readStream(con.getInputStream());

		}catch(Exception e){
			e.printStackTrace();
		}finally{
			con.disconnect();
		}
		return response;		
	}


	private String readStream(InputStream in){
		BufferedReader reader = null;
		StringBuilder builder = new StringBuilder();

		try{
			reader =new  BufferedReader(new InputStreamReader(in));
			String line = null;
			while((line = reader.readLine()) !=null){
				builder.append(line + "\n");
			}			

		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(reader !=null){
				try{
					reader.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
		return builder.toString();
	}

}
